//创建用户相关的小仓库
import { defineStore } from 'pinia'
import type { ResponseData } from 'dto/globalDto.ts'
import { reqLogin, getUserInfo } from '@/api/user'
import type { UserState } from './types/type'
import type {
  loginInDto,
  LoginOutDto,
  UserInfoDto,
} from 'dto/login/loginDto.ts'
import { set_token, get_token } from '@/utils/token'
//引入路由
import { constantRouters } from '@/router/routers'

const useUserStore = defineStore('User', {
  // 小仓库存储数据的地方
  state: (): UserState => {
    return {
      token: get_token(), //用户唯一标识token
      menuRouters: constantRouters, //存储生成菜单数据
      userName: '', //用户名
      avatar: '', //用户头像
    }
  },
  //异步|逻辑的地方
  actions: {
    /**
     * 登录
     * @param data 登录账号和密码
     * @returns token
     */
    async userLogin(data: loginInDto) {
      const result: ResponseData<LoginOutDto> = await reqLogin(data)
      if (result.code == 200) {
        this.token = result.data.token
        set_token(result.data.token)
        return 'ok'
      } else {
        return Promise.reject(new Error(result.message))
      }
    },

    /**
     * 获取用户信息
     * @param
     * @returns 类型：UserInfoDto
     */
    async getUserInfo() {
      const result: ResponseData<UserInfoDto> = await getUserInfo()
      if (result.code == 200) {
        this.userName = result.data.username
        this.avatar = result.data.avatar
        return 'ok'
      } else {
        return Promise.reject(new Error(result.message))
      }
    },

    //退出登录:清空token、userName、avatar
    useLogOut() {
      localStorage.removeItem('TOKEN')
      ;(this.token = null), (this.userName = null), (this.avatar = null)
    },
  },
  getters: {},
})

export default useUserStore
